package com.tailyou.hms.firstapp.act;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.tailyou.hms.firstapp.R;
import com.tailyou.hms.firstapp.frg.NewsFragment;

import java.util.ArrayList;
import java.util.List;

public class TabLayoutActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager2 vpFrg;
    private List<String> titles = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);
//        找到控件
        tabLayout = findViewById(R.id.tabLayout);
        vpFrg = findViewById(R.id.vpFrg);
//        准备数据
        titles.add("推荐");
        titles.add("热榜");
        titles.add("抗疫");
        titles.add("国际");
        titles.add("生活");
        fragments.add( NewsFragment.newInstance("推荐"));
        fragments.add( NewsFragment.newInstance("热榜"));
        fragments.add( NewsFragment.newInstance("抗疫"));
        fragments.add( NewsFragment.newInstance("国际"));
        fragments.add( NewsFragment.newInstance("生活"));

        vpFrg.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return fragments.size();
            }
        });

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, vpFrg, true, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles.get(position));
            }
        });
        tabLayoutMediator.attach();
    }

}